package com.zb.manager.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.zb.model.EditImgMsg;
import com.zb.model.ListMsg;
import com.zb.service.ListMsgService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class ListMsgAction {
	
	@Autowired(required=true)
	private ListMsgService ss;
	
	/**
	 * 普通文件上传
	 * @param file
	 * @param request
	 * @throws IOException
	 */
	@PostMapping("/upload")
	public void upload(MultipartFile file,HttpServletRequest request) throws IOException {
		System.out.println("=========>"+file);
		System.out.println("====filename=====>"+file.getOriginalFilename());
		String fileName = file.getOriginalFilename();
		//设置上传路径
		String path = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\wangTest\\";
		try {
			FileOutputStream fos = new FileOutputStream(path + fileName);
			IOUtils.copy(file.getInputStream(), fos);
			fos.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 富文本编辑器图片回显
	 * @param myFileName
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/editorImgUpload",method=RequestMethod.POST)
	public  String fileUploadTest(MultipartFile myFileName,HttpServletRequest request,HttpServletResponse response) {
		String url;
		if (myFileName != null) {
			String fileName = myFileName.getOriginalFilename();
			String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());//解析文件后缀名
			String realName = UUID.randomUUID().toString() + fileNameExtension;//重新生成文件名
			String realPath = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\wangTest\\"; //定义文件存放位置（在该服务器的哪个地方存放图片）
			url="http://127.0.0.1:8080/moyissm/static/wangTest/"+realName; //设置该图片的访问路径
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(realPath + realName);
				IOUtils.copy(myFileName.getInputStream(), fos); //将从客户端接收到的图片以字节流的形式输出到存放文件的地方
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			List<String> imgUrlList = new ArrayList<String>();
			imgUrlList.add(url);
			EditImgMsg eim = new EditImgMsg();
			eim.setErrno(0);
			eim.setData(imgUrlList);
			return new Gson().toJson(eim);
		}else {
			return null;
		}
	}
	
	/**
	 * 新增清单
	 * 先判断各参数是否为空，然后接收文章，上传文章，然后接收文章封面，然后创建ListMsg，保存到数据库
	 * @param value
	 * @param articleName
	 * @param articleType
	 * @param articleCover
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/storefiles",method=RequestMethod.POST)
	public int storeFiles(String value,String articleName,int articleType,MultipartFile articleCover,HttpServletRequest request){
		//判断值是否为空
		System.out.println("====articleName==>"+articleName+"====");
		System.out.println("====articleType==>"+articleType);
		System.out.println("====articleCover==>"+articleCover);
		if(articleName==null||articleName.equals("")||articleName.equals(" ")) {
			request.setAttribute("msg", "没有填写文章名称，请刷新后重新填写！！");
			return 2;
		}
		if(articleType==0) {
			request.setAttribute("msg", "没有选择文章类型，请刷新后重新填写！！");
			return 3;
		}
		if(articleCover==null) {
			request.setAttribute("msg", "没有选择文章封面，请刷新后重新填写！！");
			return 4;
		}
		
		//接收文章，传输到服务器
		System.out.println("=========>"+value);
		String aName =articleType+"-"+articleName + "-" +UUID.randomUUID().toString(); //文章名字设置： 36位随机数-文章类型的数字表示-文章名。html
		//设置上传路径
		//String path = "C:\\program_Files\\tomcat\\apache-tomcat-8.5.32-windows-x64\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\list\\"; //设置访问路径
		String path = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\list\\"; //设置本地访问路径
		try {
			FileWriter fw = new FileWriter(path+aName+".html"); //创建文件
			value="<html>" + 
					"	<head>" + 
					"<meta http-equiv=\'Content-Type\' content=\'text/html; charset=gbk\' />"+
					"		<title></title>" + 
					"	</head>" + 
					"	<body>" + value+
					"	</body>" + 
					"</html>";
			fw.write(value);  //以字符流写数据
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//生成访问URL
		String listurl = "https://127.0.0.1:8080/moyissm/static/list/"+aName+".html";
		System.out.println("===url:====>"+listurl);
		
		//接收封面，上传到服务器
		String fileName = articleCover.getOriginalFilename(); //获取图片名
		String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());//解析文件后缀名
		String realName = UUID.randomUUID().toString() + fileNameExtension;//重新生成文件名
		String realPath = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\listphoto\\"; //定义文件存放位置（在该服务器的哪个地方存放图片）
		String photourl="http://127.0.0.1:8080/moyissm/static/listphoto/"+realName; //设置该图片的访问路径
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(realPath + realName);
			IOUtils.copy(articleCover.getInputStream(), fos); //将从客户端接收到的图片以字节流的形式输出到存放文件的地方
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//创建entity，上传到数据库
		ListMsg lm = new ListMsg();
		lm.setList_id(UUID.randomUUID().toString());
		lm.setList_name(articleName);
		lm.setList_type(articleType);
		lm.setList_url(listurl);
		lm.setList_photo(photourl);
		return ss.addListMsg(lm);
	}
	
	/**
	 * 清单管理-访问前加载
	 * 分页获取
	 * @param request
	 * @param mm
	 * @param pageNo
	 * @param type
	 * @return
	 */
	@GetMapping("/listManagerInit")
	public String listManagerInit(HttpServletRequest request, ModelMap mm,@RequestParam(defaultValue="1",required=true,value="pageNo")Integer pageNo,int type){
		Integer pageSize = 8;
		PageHelper.startPage(pageNo, pageSize);
		List<ListMsg> listmsgs = ss.selectListMadByType(type);
		PageInfo<ListMsg> lms  = new PageInfo<ListMsg>(listmsgs);
		mm.addAttribute("pageInfo",lms);
		request.setAttribute("size", listmsgs.size());
		request.setAttribute("type", type);
		return "lcx/listManager-show";
	}
	
	/**
	 * 清单管理-删除清单
	 * @param listId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/dellistbyid")
	public int dellistbyid(String listId){
		return ss.delListById(listId);
	}
}